'''
Created on Mar 21, 2016

@author: JimmyMo
'''
import pika
import sys
from dispatchtarget import DispatchTarget
import logging

class DispatchTarget_RabbitMQ(DispatchTarget):
    def __init__(self, host, queue_name, routing_key, message_builder):
        super(DispatchTarget_RabbitMQ, self).__init__()
        self.host = host
        self.queue_name = queue_name
        self.routing_key = routing_key
        self.message_builder = message_builder;
#     def _parse_options(self):
#         self.host = "localhost"
    def dispatch_to(self):
        connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host)) 
        channel = connection.channel() 
        channel.queue_declare(queue=self.queue_name) 
#         message = ' '.join(sys.argv[1:]) or "info: Hello World!"
#         message = self.construct_message()
        message = self.message_builder.build()
        channel.basic_publish(exchange='', routing_key=self.routing_key, body=message) 
#         print(" [x] Sent payload...") 
        logging.info(" [x] Sent payload... Dispatching to queue [%s], routing_key [%s] , message is [%s]..." % (self.queue_name, self.routing_key, message))
        connection.close()
    def construct_message(self, msg="info: Hello World!"):
#         message = ' '.join(sys.argv[1:]) or "info: Hello World!"
        
        return msg